<template>
  <div class="data-statistics">
    <section class="statistics-bread-crumb top-box">
      <BreadCrumb>
        <template #custom>
          <div class="classify-box">
            <div v-for="classify in classifyList" :key="classify.id" :class="['classify-item', coreParam.channel == classify.id && 'active']" @click="classifyClick(classify)">
              <div class="classify-content">
                <img v-if="coreParam.channel == classify.id" :src="classify.activeSrc" alt="" />
                <img v-else :src="classify.src" alt="" />
                <span>{{ classify.name }}</span>
              </div>
              <div v-if="coreParam.channel == classify.id" class="line"></div>
            </div>
          </div>
        </template>
      </BreadCrumb>
    </section>
    <!-- 中间 -->
    <div class="center-box">
      <div class="center-box-left">
        <div class="cum-user">
          <span>累计用户数</span>
          <span class="num">{{ core.total_users }}</span>
        </div>
        <div class="today-data">
          <div
            v-for="item in todayList"
            :key="item.id"
            :class="['today-item', trendParam.type == item.id && 'active', item.hide && 'hide', coreParam.channel === 7 && (item.id === 2 || item.id === 6) && 'prevent-click']"
            @click="changeItem(item.id)"
          >
            <div class="today-item-left">
              <div class="circle">
                <div class="svg-icon flex-0">
                  <img class="icon" :src="item.icon" alt="" />
                </div>
              </div>
              <span>{{ item.name }}</span>
            </div>
            <div><span v-if="item.hasMoney">￥</span>{{ item.hasRate ? formatPercentUnit(item.num) : item.num }}</div>
          </div>
        </div>
      </div>
      <div v-loading="trendLoading" class="center-box-right">
        <div class="top-time">
          <div>{{ title }}</div>
          <div>
            <el-date-picker
              v-model="trendDateRange"
              style="width: 300px; margin-bottom: 20px;"
              type="daterange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="rangeShortcuts"
              @change="timeChange"
            />
          </div>
        </div>
        <div v-if="trendParam.type == 2" class="overview">
          <div>
            所选区间用户增长总数<span>{{ totalData }}</span>
          </div>
          <div>
            单日最高增长数<span>{{ maxData }}</span>
          </div>
          <div>
            单日最低增长数<span>{{ minData }}</span>
          </div>
        </div>
        <div v-if="trendParam.type == 3" class="overview">
          <div>
            所选区间用户成交总数<span>￥{{ totalData.toFixed(2) }}</span>
          </div>
          <div>
            单日最高成交值<span>￥{{ maxData.toFixed(2) }}</span>
          </div>
          <div>
            单日最低成交值<span>￥{{ minData.toFixed(2) }}</span>
          </div>
        </div>
        <div v-if="trendParam.type == 4" class="overview">
          <div>
            所选区间订单总数<span>{{ totalData }}</span>
          </div>
          <div>
            单日最高订单数<span>{{ maxData }}</span>
          </div>
          <div>
            单日最低订单数<span>{{ minData }}</span>
          </div>
        </div>
        <div v-if="trendParam.type == 5" class="overview">
          <div>
            所选区间活跃用户总数<span>{{ totalData }}</span>
          </div>
          <div>
            单日最高活跃数<span>{{ maxData }}</span>
          </div>
          <div>
            单日最低活跃数<span>{{ minData }}</span>
          </div>
        </div>
        <div v-if="trendParam.type == 6" class="overview">
          <div>
            所选区间最高转化率<span>{{ formatPercentUnit(maxData) }}</span>
          </div>
          <div>
            所选区间最低转化率<span>{{ formatPercentUnit(minData) }}</span>
          </div>
        </div>
        <div v-if="trendParam.type == 7" class="overview">
          <div>
            最高日均客单价<span>￥{{ maxData.toFixed(2) }}</span>
          </div>
          <div>
            最低日均客单价<span>￥{{ minData.toFixed(2) }}</span>
          </div>
        </div>
        <div class="chart">
          <KLineChart
            width="100%"
            height="300px"
            x-type="date"
            y-type="number"
            :x-data="xData"
            :y-data="yData"
            :tooltip="tooltip"
            :options="option"
          />
        </div>
      </div>
    </div>
    <!-- 底部表格 -->
    <section v-show="coreParam.channel !== 7" class="base-page-container bottom-box">
      <div class="bottom-box-top">
        <div class="tabs">
          <div
            v-for="item in tabs"
            :key="item.id"
            :class="[
              item.id == 0 && 'left',
              item.id == 1 && 'right',
              retainParam.type == item.id && item.id == 0 && 'active',
              retainParam.type == item.id && item.id == 1 && 'active2'
            ]"
            @click="changeTab(item.id)"
          >
            {{ item.name }}
          </div>
        </div>
        <div>
          <el-date-picker
            v-model="retainDateRange"
            style="width: 300px"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            :shortcuts="rangeShortcuts"
            @change="retainTimeChange"
          />
        </div>
      </div>
      <ColorfulTable v-loading="loading" class="table" :table-data="tableData" :column="columns" />
    </section>
  </div>
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import BreadCrumb from '@/components/base-bread-crumb/index.vue';
import { ref, computed } from 'vue';
import { KLineChart } from '@/components/k-charts';
import { statCore, statTrend, statRetained } from '@/api/crm-kgj/statistics';
import { saleSummaryCore, saleSummaryTrend } from '@/api/crm-kgj/salesummary';
import { ColorfulTable } from '@/components/colorful-table';
import { formatPercent, formatPercentUnit, toolGetDataPageRangeShortCuts as rangeShortcuts, toolGetCountInitDateRange } from '@/utils';
import {
  img_1,
  img_2,
  img_3,
  img_4,
  img_5,
  img_6,
  img_7,
  img_active_1,
  img_active_2,
  img_active_3,
  img_active_4,
  img_active_5,
  img_active_6,
  img_active_7,
  lecturerUser1,
  lecturerRmb,
  lecturerFile,
  lecturerChart,
  lecturerRefresh
} from './img-path';
defineOptions({
  name: 'KgjDataStatisticsIndex'
});
// 顶部tabs
const classifyList = [
  {
    name: '全渠道',
    id: 0,
    src: img_1,
    activeSrc: img_active_1
  },
  {
    name: '讲师渠道',
    id: 1,
    src: img_2,
    activeSrc: img_active_2
  },
  {
    name: '代理渠道',
    id: 2,
    src: img_3,
    activeSrc: img_active_3
  },
  {
    name: '销售渠道',
    id: 7,
    src: img_3,
    activeSrc: img_active_3
  },
  {
    name: 'PC注册',
    id: 3,
    src: img_4,
    activeSrc: img_active_4
  },
  {
    name: '安卓注册',
    id: 4,
    src: img_5,
    activeSrc: img_active_5
  },
  {
    name: 'IOS注册',
    id: 5,
    src: img_6,
    activeSrc: img_active_6
  },
  {
    name: '小程序注册',
    id: 6,
    src: img_7,
    activeSrc: img_active_7
  }
];
const classifyClick = (val: Record<string, any>) => {
  coreParam.value.channel = val.id;
  trendParam.value.channel = val.id;
  retainParam.value.channel = val.id;
  if (val.id === 7) {
    getSaleSummaryCore();
    changeItem(3);
    return;
  }
  init();
};
const { initDate, initDtArr } = toolGetCountInitDateRange();

// 获取销售渠道统计数据
const getSaleSummaryCore = async () => {
  core.value.total_users = 0;
  core.value.new_users = 0;
  core.value.change_ratio = 0;

  const res = await saleSummaryCore();
  if (!res) return;
  const { data: result } = res;
  core.value.gmv = result.new_total_price;
  core.value.order = result.new_order_count;
  core.value.atv = result.avt;
};
const title = ref('用户增长趋势');
const changeItem = (val: number) => {
  if (coreParam.value.channel === 7 && (val === 2 || val === 6)) return;
  if (trendParam.value.type === val) return;
  trendParam.value.type = val;

  switch (val) {
    case 2:
      title.value = '用户增长趋势';
      break;
    case 3:
      title.value = '成交趋势';
      break;
    case 4:
      title.value = '订单趋势';
      break;
    case 5:
      title.value = '活跃用户趋势';
      break;
    case 6:
      title.value = '转化率趋势';
      break;
    case 7:
      title.value = '客单价趋势';
      break;
  }
  getTrend();
};
const timeChange = (val: any[]) => {
  const { from, to, range } = timeDeal(val);
  trendDateRange.value = range;
  trendParam.value.fromDt = from;
  trendParam.value.toDt = to;
  getTrend();
};

// 底部tabs
const tabs = [
  {
    id: 0,
    name: '新用户留存'
  },
  {
    id: 1,
    name: '活跃用户留存'
  }
];
const changeTab = (val: number) => {
  retainParam.value.type = val;
  if (val === 0) {
    columns.value[1] = {
      label: '新增用户',
      prop: 'users',
      type: 'normal'
    };
  } else {
    columns.value[1] = {
      label: '活跃用户',
      prop: 'users',
      type: 'normal'
    };
  }
  getData();
};
const retainDateRange = ref<any[]>(initDate);
const retainTimeChange = (val: any[]) => {
  const { from, to, range } = timeDeal(val);
  retainDateRange.value = range;
  retainParam.value.fromDt = from;
  retainParam.value.toDt = to;
  getData();
};
const timeDeal = (val: any[]) => {
  let res = {
    to: initDtArr[0],
    from: initDtArr[1],
    range: [] as any[]
  };
  if (val && val.length) {
    const from = dayjs(val[0]).format('YYYYMMDD');
    const to = dayjs(val[1]).format('YYYYMMDD');
    res = {
      from,
      to,
      range: [from, to]
    };
  }
  return res;
};
// 表格
const columns = ref([
  {
    label: '时间',
    prop: 'ts',
    width: 180,
    type: 'time',
    format: 'YYYY-MM-DD'
  },
  {
    label: '新增用户',
    prop: 'users',
    type: 'normal'
  },
  {
    label: '1天后',
    prop: 'day1_cnt'
  },
  {
    label: '2天后',
    prop: 'day2_cnt'
  },
  {
    label: '3天后',
    prop: 'day3_cnt'
  },
  {
    label: '4天后',
    prop: 'day4_cnt'
  },
  {
    label: '5天后',
    prop: 'day5_cnt'
  },
  {
    label: '6天后',
    prop: 'day6_cnt'
  },
  {
    label: '7天后',
    prop: 'day7_cnt'
  },
  {
    label: '14天后',
    prop: 'day14_cnt'
  },
  {
    label: '30天后',
    prop: 'day30_cnt'
  },
  {
    label: '60天后',
    prop: 'day60_cnt'
  }
]);

const option = {
  showMarkLine: true
};
const tooltip = (params: any) => {
  // 图例数据
  let itemStr = '';
  params.forEach((item: any) => {
    itemStr += `
    <div style="width:100%;margin-bottom:10px;color: #fff;">${dayjs.unix(item.axisValue).format('MM-DD')}</div>
    <div class="row">
      <div class="sample" style="background: ${item.color}"></div>
      <div class="name">${
  trendParam.value.type === 2
    ? '用户新增'
    : trendParam.value.type === 3
      ? '成交金额'
      : trendParam.value.type === 4
        ? '订单数'
        : trendParam.value.type === 5
          ? '活跃用户'
          : trendParam.value.type === 6
            ? '转化率'
            : '日均客单价'
}：</div>
                <div class="value">
                  <div class="value-inner">
                    <span class="number">${toolNumFormat(item.value)}</span>
                  </div>
                </div>
          </div>`;
  });

  const str = `<div class="chart-tooltip line">
    ${itemStr}
  </div>`;

  return str;
};
// 获取数据
const coreParam = ref({
  channel: 0
});

const trendParam = ref({
  channel: 0,
  type: 2,
  fromDt: initDtArr[0],
  toDt: initDtArr[1]
});
const trendDateRange = ref<any[]>(initDate);
const retainParam = ref({
  channel: 0,
  type: 0,
  fromDt: initDtArr[0],
  toDt: initDtArr[1]
});
const todayList = computed(() => {
  return [
    {
      id: 2,
      name: '今日新增',
      num: core.value.new_users,
      icon: lecturerUser1
    },
    {
      id: 3,
      name: '今日成交',
      num: core.value.gmv,
      hasMoney: true,
      icon: lecturerRmb
    },
    {
      id: 4,
      name: '今日订单',
      num: core.value.order,
      icon: lecturerFile
    },
    {
      id: 7,
      name: '今日客单',
      num: core.value.atv,
      hasMoney: true,
      icon: lecturerChart
    },
    {
      id: 6,
      name: '累计转化',
      num: core.value.change_ratio,
      hasRate: true,
      icon: lecturerRefresh
    },
    {
      id: 5,
      name: '今日活跃',
      num: core.value.act_cnt,
      hide: true
    }
  ];
});
const core = ref<any>({});
const getCore = async () => {
  const res = await statCore(coreParam.value);
  const data = res.data;
  core.value = data;
};
let xData = ref<any[]>([]);
let yData = ref<any[]>([]);
let minData = ref(0);
let maxData = ref(0);
let totalData = ref(0);
const toolNumFormat = (val: number) => {
  if (trendParam.value.type === 3 || trendParam.value.type === 7) {
    return `￥${Number(val.toFixed(1))}`;
  } else if (trendParam.value.type === 6) {
    return `${val}%`;
  }
  return val;
};
const trendLoading = ref(false);
const getTrend = async () => {
  trendLoading.value = true;
  let res: Record<string, any> = {};
  let chartData: any[] = [];
  xData.value = [];
  yData.value = [];
  minData.value = 0;
  maxData.value = 0;
  totalData.value = 0;
  if (coreParam.value.channel === 7) {
    // 销售渠道下走其他接口
    // 1 成交趋势 2 订单趋势  3 跟踪增长趋势 4 到期趋势 5 累计成交趋势 6 客单价趋势
    const obj: Record<string, any> = {
      3: 1,
      4: 2,
      7: 6
    };
    const params = {
      ...trendParam.value,
      type: obj[trendParam.value.type],
      channel: undefined
    };
    res = await saleSummaryTrend(params);
  } else {
    res = await statTrend(trendParam.value);
    console.log(res, 456);
  }
  trendLoading.value = false;
  const { data: result, min, max, total } = res.data;
  minData.value = min;
  maxData.value = max;
  totalData.value = total;
  result.forEach((item: any) => {
    let value: any = item.value;
    if (trendParam.value.type === 6) value = formatPercent(value);
    chartData.push(value);
    xData.value.push(item.ts);
  });
  yData.value = [
    {
      name: '趋势图',
      color: '#307AF2',
      data: chartData
    }
  ];
};

const tableData = ref([]);
const loading = ref(false);
const getData = async () => {
  tableData.value = [];
  loading.value = true;
  const res = await statRetained(retainParam.value);
  loading.value = false;
  const { data } = res.data;
  tableData.value = data;
};
const init = () => {
  getCore();
  getTrend();
  getData();
};
init();
</script>

<style lang="scss" scoped>
.data-statistics {
  .flex-0 {
    flex: 0 0 auto;
  }

  .top-box {
    .classify-box {
      display: flex;
      justify-content: space-around;
      margin: 30px 0 20px;
      font-size: 18px;
      font-weight: 600;
      line-height: 22px;
      color: #86909c;

      .classify-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        cursor: pointer;

        &.active {
          color: #307af2;
        }

        .classify-content {
          display: flex;
          align-items: center;
        }

        img {
          width: 16px;
          margin-right: 12px;
        }

        .line {
          width: 44px;
          height: 4px;
          margin-top: 8px;
          background: #307af2;
          border-radius: 2px;
        }
      }
    }
  }

  .center-box {
    display: flex;
    margin: 16px 0;

    .center-box-left {
      min-width: 288px;
      max-width: 288px;
      margin-right: 10px;

      .cum-user {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 88px;
        font-size: 16px;
        font-weight: 500;
        color: #f2f3f5;
        background: linear-gradient(94.63deg, #4080ff 0%, #6db9ff 100%);
        border-radius: 4px;

        .num {
          margin-left: 20px;
          font-size: 28px;
          font-weight: 600;
        }
      }

      .today-data {
        padding: 20px 24px 6px;
        margin-top: 10px;
        font-size: 14px;
        font-weight: 500;
        line-height: 22px;
        color: #4e5969;
        background: #fff;

        .today-item {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 16px 24px;
          margin-bottom: 14px;
          cursor: pointer;
          background: #f7f8fa;
          border-radius: 2px 0 0 2px;

          .today-item-left {
            display: flex;
            align-items: center;
          }

          .circle {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 20px;
            height: 20px;
            margin-right: 8px;
            background: #c9cdd4;
            border-radius: 50%;

            .icon {
              color: #fff;
            }

            .icon2 {
              transform: rotate(90deg);
            }
          }

          &.prevent-click {
            pointer-events: none;
          }

          .svg-icon {
            display: block;
            padding: 4px;
            overflow: hidden;
            background-color: #c9cdd4;
            border-radius: 50%;

            img {
              display: block;
              width: 20px;
              height: 20px;
              filter: drop-shadow(#fff -200px 0);
              transform: translateX(200px);
            }
          }

          &.hide {
            visibility: hidden;
          }

          &.active {
            color: #fff;
            background: #307af2;

            .svg-icon {
              background-color: #fff;

              img {
                filter: drop-shadow(#307af2 -200px 0);
              }
            }

            .circle {
              background: #fff;

              .icon {
                color: #307af2;
              }
            }
          }
        }
      }
    }

    .center-box-right {
      flex: 1;
      padding: 24px;
      background: #fff;

      .top-time {
        display: flex;
        justify-content: space-between;
        font-size: 18px;
        font-weight: 500;
        line-height: 22px;
        color: #4e5969;
      }

      .overview {
        display: flex;
        align-items: center;
        padding-left: 24px;
        font-size: 12px;
        line-height: 42px;
        color: #86909c;
        background: #e8f3ff;
        border-radius: 4px;

        span {
          margin: 0 30px 0 6px;
          font-size: 16px;
          font-weight: 600;
          color: #4e5969;
        }
      }

      .chart {
        margin-top: 40px;
      }
    }
  }

  .bottom-box {
    .bottom-box-top {
      display: flex;
      align-items: baseline;
      justify-content: space-between;
      margin-bottom: 16px;

      .tabs {
        display: flex;

        > div {
          box-sizing: border-box;
          min-width: 88px;
          padding: 5px 16px;
          font-size: 14px;
          font-style: normal;
          font-weight: 400;
          line-height: 22px;
          color: #606266;
          text-align: center;
          letter-spacing: -.01px;
          cursor: pointer;

          &.active {
            color: #fff;
            background-color: #4975e9;
            border: 1px solid #4975e9;
            border-radius: 4px 0 0 4px;
          }

          &.active2 {
            color: #fff;
            background-color: #4975e9;
            border: 1px solid #4975e9;
            border-radius: 0 4px 4px 0;
          }
        }

        .left {
          border: 1px solid #dcdfe6;
          border-radius: 4px 0 0 4px;
        }

        .right {
          border: 1px solid #dcdfe6;
          border-radius: 0 4px 4px 0;
        }
      }
    }
  }
}
</style>
